const localCache = {
  set(key: string, value: any) {
    if (key != null && value != null) {
      uni.setStorageSync(key, value);
    }
  },
  get(key: string) {
    if (key == null) {
      return null;
    }
    return uni.getStorageSync(key);
  },
  setJSON(key: string, jsonValue: any) {
    if (jsonValue != null) {
      try {
        this.set(key, JSON.stringify(jsonValue));
      } catch (error) {
        console.error('Cache setJSON error:', error);
      }
    }
  },
  getJSON(key: string) {
    try {
      const value = this.get(key);
      if (value == null || value === undefined) {
        return null;
      }
      // 确保值是字符串类型
      if (typeof value !== 'string') {
        return value;
      }
      // 检查是否为空字符串
      if (value === '' || value.trim() === '') {
        return null;
      }
      // 尝试解析JSON
      return JSON.parse(value);
    } catch (error) {
      console.error('Cache getJSON error:', error);
      // 清除无效的缓存数据
      this.remove(key);
      return null;
    }
  },
  remove(key: string) {
    uni.removeStorageSync(key);
  }
};

export default {
  /**
   * 本地缓存
   */
  local: localCache
};
